<?php
class EquipmentController extends Zend_Controller_Action
{
	private $_arrParam;
	private $_paniging = array('rowCount'=> 15, 'pageRange'=> 10);
	private $_userInfo;
	private $_config;
    private $_layout;
    public function init ()
    {
        $acl = new My_Acl();
        $auth = $acl->checkAllowed($this->_request);
        
        $this->_userInfo = $auth->getIdentity();
        $this->_arrParam['userId'] = $this->_userInfo['userId'];
        
    	//init value for pagining
    	$pageNumber = $this->_request->getParam('page',1);
    	$this->_paniging['page'] = $pageNumber;
    	$this->_arrParam['panigator'] = $this->_paniging;
		$this->_config = new Zend_Config_Ini(CONFIG_PATH . '/columns.ini',APPLICATION_ENV);
    }
    public function checkcodeAction(){
	    Zend_Layout::getMvcInstance()->disableLayout();
	    $this->_helper->viewRenderer->setNoRender();
        $code               = $this->_getParam('code');
        
        $model_equipment        = new Default_Model_Equipment();
        $equipment_check = $model_equipment->checkCode($code);
        if($equipment_check){
            echo 'có';
        }else{
            echo 'không';
        }
        
    }
    public function getcodeAction(){
	    Zend_Layout::getMvcInstance()->disableLayout();
	    $this->_helper->viewRenderer->setNoRender();
        $category           = (int)($this->_getParam('category'));
        $owner              = $this->_getParam('owner');
        
        $model_category           = new Default_Model_Category();
        $category_check = $model_category->getDataById($category);
        if($category_check){
            $categoryCode = $category_check['categoryCode'];
            $owner_list = $this->_config->owner->toArray();
            foreach($owner_list as $key=>$row){
                if($row['name'] == $owner){
                    $ownerCode = $row['code'];
                    break;
                }
            }
            
            if(isset($categoryCode) && isset($ownerCode)){
                $model_equipment        = new Default_Model_Equipment();
                $code = "$categoryCode-$ownerCode-";
                if($category_check['categoryId'] == 15){
                    $code = $categoryCode;
                }
                $equipment_check = $model_equipment->checkMaxCode($code);
                if($equipment_check){
                    //echo $categoryCode,'-',$ownerCode;
                    if($category_check['categoryId'] == 15){
                        $stt =  (int)(substr($equipment_check['code'],3)) + 1;
                    }else{
                        $stt =  (int)(substr($equipment_check['code'],-3)) + 1;
                    }
                    $stt = '000'.$stt;
                    $stt =  substr($stt,-3);
                }else{
                    $stt = '001';
                }
                if($category_check['categoryId'] == 15){
                    echo $categoryCode,$stt;
                }else{
                    echo $categoryCode,'-',$ownerCode,'-',date("y"),$stt;
                }
            }
        }
    }

    public function statisticAction ()
    {
        $model_equipment    = new Default_Model_Equipment();
        $model_category     = new Default_Model_Category();
        $model_project      = new Default_Model_Project();
        $this->view->model_equipment = $model_equipment;
        $this->view->model_category = $model_category;
        
        $ownerList          = $this->_config->owner;
        $projectList        = $model_project->getAllData();
        $categoryList       = $model_category->getAllData();
        $this->view->ownerList      = $ownerList;
        $this->view->projectList    = $projectList;
        $this->view->categoryList   = $categoryList;
                
        $params['categoryId'] 	= $this->getRequest()->getParam('categoryId', '');
        $params['submit'] 	= $this->getRequest()->getParam('btn-search');
        if($params['submit'] || $params['categoryId']){
            if(!is_array($params['categoryId'])){
                $params['categoryId'][0] = $params['categoryId'];
            }
            
            $categorySearch = $params['categoryId'];
            $countCate = count($categorySearch);
            $arrCate = array();
            foreach($categorySearch as $cate){
                $temp = $model_category->getDataByID($cate);
                if($temp){
                    $arrCate[] = $temp['categoryCode'];
                }else{
                    $arrCate[] = $cate;
                }
            }
            $this->view->arrCate = $arrCate;
            
            $arrCountEquipment = array();
            foreach($projectList as $project){
                foreach($ownerList as $owner){
                    foreach($categorySearch as $cate){
                        $count = $model_equipment->countEquipmentByProject($project['projectId'],$owner->code,$cate);
                        if(isset($count) && $count['Sum']){
                            $count['Sum'] = $count['Sum'];
                        }else{
                            $count['Sum'] = '';
                        }
                        $arrCountEquipment[$project['projectId']][$owner->code][$cate] = $count['Sum'];
                    }
                }
            }
            $this->view->arrCountEquipment = $arrCountEquipment;
        
            $this->view->categorySearch = $params['categoryId'];
            #echo '<pre>',print_r($params['categoryId']),'</pre>';exit;
        }
        
    }

    public function statisticexportAction ()
    {
	    Zend_Layout::getMvcInstance()->disableLayout();
	    $this->_helper->viewRenderer->setNoRender();
        
        $model_equipment    = new Default_Model_Equipment();
        $model_category     = new Default_Model_Category();
        $model_project      = new Default_Model_Project();
        
        $ownerList          = $this->_config->owner;
        $projectList        = $model_project->getAllData();
        $categoryList       = $model_category->getAllData();
        
        $params['categoryId'] 	= $this->getRequest()->getParam('categoryId', '');
        if(isset($params['categoryId'])){
            if(!is_array($params['categoryId'])){
                $params['categoryId'][0] = $params['categoryId'];
            }
        }else{
            return $this->_helper->redirector('statistic', 'equipment');
        }
        $categorySearch = $params['categoryId'];
        $countCate = count($categorySearch);
        $arrCate = array();
        foreach($categorySearch as $cate){
            $temp = $model_category->getDataByID($cate);
            if($temp){
                $arrCate[] = $temp['categoryCode'];
            }else{
                $arrCate[] = $cate;
            }
        }
        $arrCountEquipment = array();
        foreach($projectList as $project){
            foreach($ownerList as $owner){
                foreach($categorySearch as $cate){
                    $count = $model_equipment->countEquipmentByProject($project['projectId'],$owner->code,$cate);
                    if(isset($count) && $count['Sum']){
                        $count['Sum'] = $count['Sum'];
                    }else{
                        $count['Sum'] = '';
                    }
                    $arrCountEquipment[$project['projectId']][$owner->code][$cate] = $count['Sum'];
                }
            }
        }
        #echo '<pre>',print_r($arrCountEquipment),'</pre>';exit;
        
        
        error_reporting(E_ERROR | E_WARNING | E_PARSE);
			
        $workbook = My_Pear::getInstanceSpreadsheet();
	    $workbook->setVersion(8, 'utf-8'); 
		$worksheet1 = &$workbook->addWorksheet('Statistic'); 
        $worksheet1->setInputEncoding('utf-8');
        $worksheet1->setColumn(0,0,6);
        $worksheet1->setColumn(2,25,6);
        $worksheet1->setColumn(1,1,35);
        
		//end style	
		$header = &$workbook->addFormat(); 
		$header->setBold(); 
		$header->setColor('white'); 
        $header->setFgColor('50'); 
		$header->setAlign('vcentre');
		$header->setHAlign('center'); 
		$header->setVAlign('center'); 
		$header->setBorder(1); 	
        $header->setTextWrap();

		$textStyle = &$workbook->addFormat(); 
		$textStyle->setAlign('vcentre');
		$textStyle->setHAlign('center'); 
		$textStyle->setVAlign('center'); 
		$textStyle->setHAlign('left');
        $textStyle->setBorder(1);
        $textStyle->setTextWrap();

		$textStyleYellow = &$workbook->addFormat(); 
		$textStyleYellow->setFgColor('43'); 
		$textStyleYellow->setAlign('vcentre');
		$textStyleYellow->setHAlign('center'); 
		$textStyleYellow->setVAlign('center'); 
		$textStyleYellow->setHAlign('left');
        $textStyleYellow->setBorder(1);
        $textStyleYellow->setTextWrap();

		$textStyleBlue = &$workbook->addFormat(); 
		$textStyleBlue->setFgColor('41'); 
		$textStyleBlue->setAlign('vcentre');
		$textStyleBlue->setHAlign('center'); 
		$textStyleBlue->setVAlign('center'); 
        $textStyleBlue->setBorder(1);
        $textStyleBlue->setTextWrap();

		$textStyleCyan = &$workbook->addFormat(); 
		$textStyleCyan->setFgColor('22'); 
		$textStyleCyan->setAlign('vcentre');
		$textStyleCyan->setHAlign('center'); 
		$textStyleCyan->setVAlign('center'); 
		$textStyleCyan->setHAlign('left');
        $textStyleCyan->setBorder(1);
        $textStyleCyan->setTextWrap();
		
		$numberSTTFormat = &$workbook->addFormat();
		$numberSTTFormat->setAlign('vcentre');
		$numberSTTFormat->setHAlign('center'); 
		$numberSTTFormat->setVAlign('center'); 
		$numberSTTFormat->setNumFormat('#,###');
        $numberSTTFormat->setBorder(1);
        $numberSTTFormat->setTextWrap();
		
		$numberSTTFormatYellow = &$workbook->addFormat();
		$numberSTTFormatYellow->setFgColor('43'); 
		$numberSTTFormatYellow->setAlign('vcentre');
		$numberSTTFormatYellow->setHAlign('center'); 
		$numberSTTFormatYellow->setVAlign('center'); 
		$numberSTTFormatYellow->setNumFormat('#,###');
        $numberSTTFormatYellow->setBorder(1);
        $numberSTTFormatYellow->setTextWrap();
		
		$numberSTTFormatBlue = &$workbook->addFormat();
		$numberSTTFormatBlue->setFgColor('41'); 
		$numberSTTFormatBlue->setAlign('vcentre');
		$numberSTTFormatBlue->setHAlign('center'); 
		$numberSTTFormatBlue->setVAlign('center'); 
		$numberSTTFormatBlue->setNumFormat('#,###');
        $numberSTTFormatBlue->setBorder(1);
        $numberSTTFormatBlue->setTextWrap();
		
		$numberSTTFormatCyan = &$workbook->addFormat();
		$numberSTTFormatCyan->setFgColor('22'); 
		$numberSTTFormatCyan->setAlign('vcentre');
		$numberSTTFormatCyan->setHAlign('center'); 
		$numberSTTFormatCyan->setVAlign('center'); 
		$numberSTTFormatCyan->setNumFormat('#,###');
        $numberSTTFormatCyan->setBorder(1);
        $numberSTTFormatCyan->setTextWrap();
		
		$numberFormat = &$workbook->addFormat();
		$numberFormat->setHAlign('right');
		$numberFormat->setVAlign('center'); 
		$numberFormat->setNumFormat('#,###');
        $numberFormat->setBorder(1);
        $numberFormat->setTextWrap();
		
		$numberFormatYellow = &$workbook->addFormat();
		$numberFormatYellow->setFgColor('43'); 
		$numberFormatYellow->setHAlign('right');
		$numberFormatYellow->setVAlign('center'); 
		$numberFormatYellow->setNumFormat('#,###');
        $numberFormatYellow->setBorder(1);
        $numberFormatYellow->setTextWrap();
		
		$numberFormatBlue = &$workbook->addFormat();
		$numberFormatBlue->setFgColor('41'); 
		$numberFormatBlue->setHAlign('right');
		$numberFormatBlue->setVAlign('center'); 
		$numberFormatBlue->setNumFormat('#,###');
        $numberFormatBlue->setBorder(1);
        $numberFormatBlue->setTextWrap();
		
		$numberFormatCyan = &$workbook->addFormat();
		$numberFormatCyan->setFgColor('22'); 
		$numberFormatCyan->setHAlign('right');
		$numberFormatCyan->setVAlign('center'); 
		$numberFormatCyan->setNumFormat('#,###');
        $numberFormatCyan->setBorder(1);
        $numberFormatCyan->setTextWrap();
        
        $num_line = 0;
        $num_column = 2;
        $worksheet1->write($num_line, 0, 'STT', $header); 
        $worksheet1->write($num_line, 1, 'Dự án', $header); 
        foreach($ownerList as $row){
            for($i = 0; $i<$countCate; $i++){
                $worksheet1->write($num_line, $num_column+$i, $row->name, $header); 
            }
            $worksheet1->setMerge($num_line, $num_column, $num_line, $num_column+$countCate-1);
            $num_column+=$countCate;
        }
        ++$num_line;
        $num_column = 2;
        $worksheet1->write($num_line, 0, 'STT', $header); 
        $worksheet1->write($num_line, 1, 'Dự án', $header);
        $worksheet1->setMerge(0, 0, 1, 0);
        $worksheet1->setMerge(0, 1, 1, 1);
        
        foreach($ownerList as $row){
            foreach($arrCate as $cate){
                $worksheet1->write($num_line, $num_column, $cate, $header); 
                ++$num_column;
            }
        }
        ++$num_line;
        $stt = 1;
        foreach($projectList as $project){
            $typeText   = $textStyle;
            $typeNumb   = $numberFormat;
            $typeSTT    = $numberSTTFormat;
//            if($stt%2 == 0){
//                $typeText   = $textStyleYellow;
//                $typeNumb   = $textStyleYellow;
//                $typeSTT    = $textStyleYellow;
//            }
                
            $num_column = 2;
            $worksheet1->write($num_line, 0, $stt, $typeSTT); 
            $worksheet1->write($num_line, 1, $project['projectName'], $typeText);
            foreach($ownerList as $owner){
                foreach($categorySearch as $cate){
                    if(isset($arrCountEquipment[$project['projectId']][$owner->code][$cate]) && $arrCountEquipment[$project['projectId']][$owner->code][$cate]){
                        $countEquipment = $arrCountEquipment[$project['projectId']][$owner->code][$cate];
                    }else{
                        $countEquipment = '';
                    }
                    $worksheet1->write($num_line, $num_column, $countEquipment, $typeNumb);
                    ++$num_column;
                }
            }
            ++$num_line; 
            ++$stt;
        }
        
		$name = "cmdb_equipment_statistic".date("dmY");
		$workbook->send("{$name}.xls"); 
		$workbook->close();
    }

    public function indexAction ()
    {
        $model_equipment        = new Default_Model_Equipment();
        $model_rolesoption      = new Default_Model_Rolesoption();
        $model_rolesprivilege   = new Default_Model_Rolesprivilege();
        $model_option           = new Default_Model_Option();
        $model_project          = new Default_Model_Project();
        $model_items            = new Default_Model_Items();
        
        // lấy phần chung: tùy chọn view của user và tùy chọn view của quyền user
        $option_user_check  = $model_option->getOptions($this->_arrParam['userId'])->toArray();
        $option_user_check  = json_decode($option_user_check['name']);
        $option_role        = $model_rolesoption->getDataByUserId($this->_arrParam['userId']);
        $temp = array();
        foreach($option_role as $row){
            $temp = array_merge($temp, json_decode($row['views']));
        }
        $temp = array_unique($temp);
        $option_views = array_intersect($temp, $option_user_check);
        $option_views = array_values($option_views);
        
        
        // Tùy chọn hiển thị cho equipment và item
		$arr_name = array();
		$arr_header = array();
        $arr_option_equipment = array('equipmentId','isGeneral','trackDate');
        $arr_option_item = array();
        foreach($option_views as $row){
        	$arr_name[] = $this->_config->views->$row->column;                      // Tất cả các cột cần hiển thị
            
        	$arr_header[] = $this->_config->views->$row->header;                    // Tên các cột cần hiển thị
            if($this->_config->views->$row->table == 'equipment')           
                $arr_option_equipment[] = $this->_config->views->$row->column;      // Các cột cần hiển thị trong table equipment
            if($this->_config->views->$row->table == 'items')
                $arr_option_item[] = $this->_config->views->$row->column;           // Các cột cần hiển thị trong table items
        }
        $this->view->arr_name = $arr_name;
        
        $this->view->arr_header = $arr_header;
        $this->view->arr_option_equipment = $arr_option_equipment;
        $this->view->arr_option_item = $arr_option_item;
        //echo '<pre>',print_r($arr_name),'</pre>';exit;
        
        // Danh sách các dự án mà user có quyền thao tác
        $provilege_role     = $model_rolesprivilege->getDataByUserId($this->_arrParam['userId']);
        
        $temp = array();
        foreach($provilege_role as $row){
            $temp = array_merge($temp, json_decode($row['projectId']));
        }
        $temp = array_unique($temp);
        $project_list = array_values($temp);
        
        // Lấy danh sách equipment (Chỉ lấy những trường user cần xem)
        $equipment_list = $model_equipment->getAllData($project_list, $arr_option_equipment, $this->_paniging['page'], $this->_paniging['rowCount'])->toArray();
      
        $equipment_count = $model_equipment->countAllData($project_list)->toArray();
       
        foreach($equipment_list as $key=>$row){
                //$equipment_list[$key]['items_list'] = $model_items->getDataByEquipmentId($row['equipmentId'],$arr_option_item)->toArray();
                $equipment_list[$key]['items_list'] = $model_items->getItems($row['equipmentId'])->toArray();
                $equipment_list[$key]['project_list'] = $model_project->getDataByEquipmentId($row['equipmentId'])->toArray();
        }
        //echo '<pre>',print_r($equipment_list),'</pre>';exit;
        $this->view->equipment_list = $equipment_list;
        
        
        $objPaginator= new My_Paginator();
        $totalItem = $equipment_count['Total'];
        $itemCountPerPage = $this->_paniging['rowCount'];
        $pageRange = $this->_paniging['pageRange'];
        $currentPage = $this->_paniging['page'];
        $panigator = $objPaginator->createPaginator($totalItem, $itemCountPerPage, $pageRange, $currentPage);
        $this->view->panigator = $panigator;
    }
    public function serverfreeAction ()
    {
        $model_equipment        = new Default_Model_Equipment();
        $model_rolesoption      = new Default_Model_Rolesoption();
        $model_rolesprivilege   = new Default_Model_Rolesprivilege();
        $model_option           = new Default_Model_Option();
        
        $model_category         = new Default_Model_Category();
        $model_project          = new Default_Model_Project();
        $model_items            = new Default_Model_Items();
        
        $provilege_role     = $model_rolesprivilege->getDataByUserId($this->_arrParam['userId']);
        $temp = array();
        foreach($provilege_role as $row){
            $temp = array_merge($temp, json_decode($row['projectId']));
        }
        $temp = array_unique($temp);
        $project_list = array_values($temp);
        
        $sortCate               = $model_category->getAllData()->toArray();
        $sortProject            = $model_project->getListData($project_list)->toArray();
        $sortOwner              = $model_items->getOwner()->toArray();
        $this->view->sortCate = $sortCate;
        $this->view->sortProject = $sortProject;
        $this->view->sortOwner = $sortOwner;
        
        // lấy phần chung: tùy chọn view của user và tùy chọn view của quyền user
        $option_user_check  = $model_option->getOptions($this->_arrParam['userId'])->toArray();
        $option_user_check  = json_decode($option_user_check['name']);
        
        $option_role        = $model_rolesoption->getDataByUserId($this->_arrParam['userId']);
        $temp = array();
        foreach($option_role as $row){
            $temp = array_merge($temp, json_decode($row['views']));
        }
        $temp = array_unique($temp);
        $option_views = array_intersect($temp, $option_user_check);
        $option_views = array_values($option_views);
        
        
        // Tùy chọn hiển thị cho equipment và item
		$arr_name = array();
		$arr_header = array();
        $arr_option_equipment = array('equipmentId','isGeneral','trackDate');
        $arr_option_item = array();
        foreach($option_views as $row){
        	$arr_name[] = $this->_config->views->$row->column;                      // Tất cả các cột cần hiển thị
        	$arr_header[] = $this->_config->views->$row->header;                    // Tên các cột cần hiển thị
            if($this->_config->views->$row->table == 'equipment')           
                $arr_option_equipment[] = $this->_config->views->$row->column;      // Các cột cần hiển thị trong table equipment
            if($this->_config->views->$row->table == 'items')
                $arr_option_item[] = $this->_config->views->$row->column;           // Các cột cần hiển thị trong table items
        }
        $this->view->arr_name = $arr_name;
        $this->view->arr_header = $arr_header;
        $this->view->arr_option_equipment = $arr_option_equipment;
        $this->view->arr_option_item = $arr_option_item;
        
        $project_list_34 		= $this->getRequest()->getParam('project_34');
        $project_list_38 		= $this->getRequest()->getParam('project_38');
        $project_list_47 		= $this->getRequest()->getParam('project_47');
        $project_list = array();
        if($project_list_34)
            $project_list[] = 34;
        if($project_list_38)
            $project_list[] = 38;
        if($project_list_47)
            $project_list[] = 47;
            
        if(!isset($project_list[0])){
            $project_list = array(34,38,47);
            $project_list_34 = 34;
            $project_list_38 = 38;
            $project_list_47 = 47;
        }
            
        $this->view->project_34 = $project_list_34;
        $this->view->project_38 = $project_list_38;
        $this->view->project_47 = $project_list_47;
        
        // Lấy danh sách equipment (Chỉ lấy những trường user cần xem)
        $equipment_list = $model_equipment->getServerFreeData($project_list, $arr_option_equipment, $this->_paniging['page'], $this->_paniging['rowCount'])->toArray();
        $equipment_count = $model_equipment->countServerFreeData($project_list)->toArray();
        
        foreach($equipment_list as $key=>$row){
                //$equipment_list[$key]['items_list'] = $model_items->getDataByEquipmentId($row['equipmentId'],$arr_option_item)->toArray();
                $equipment_list[$key]['items_list'] = $model_items->getItems($row['equipmentId'])->toArray();
                $equipment_list[$key]['project_list'] = $model_project->getDataByEquipmentId($row['equipmentId'])->toArray();
        }
        //echo '<pre>',print_r($equipment_list),'</pre>';exit;
        $this->view->equipment_list = $equipment_list;
        
        
        $objPaginator= new My_Paginator();
        $totalItem = $equipment_count['Total'];
        $itemCountPerPage = $this->_paniging['rowCount'];
        $pageRange = $this->_paniging['pageRange'];
        $currentPage = $this->_paniging['page'];
        $panigator = $objPaginator->createPaginator($totalItem, $itemCountPerPage, $pageRange, $currentPage);
        $this->view->panigator = $panigator;
    }
	public function notifyAction()
	{
        $model_equipment        = new Default_Model_Equipment();
        $model_rolesoption      = new Default_Model_Rolesoption();
        $model_rolesprivilege   = new Default_Model_Rolesprivilege();
        $model_option           = new Default_Model_Option();
        $model_project          = new Default_Model_Project();
        $model_items            = new Default_Model_Items();
        
        // lấy phần chung: tùy chọn view của user và tùy chọn view của quyền user
        $option_user_check  = $model_option->getOptions($this->_arrParam['userId'])->toArray();
        $option_user_check  = json_decode($option_user_check['name']);
        
        $option_role        = $model_rolesoption->getDataByUserId($this->_arrParam['userId']);
        $temp = array();
        foreach($option_role as $row){
            $temp = array_merge($temp, json_decode($row['views']));
        }
        $temp = array_unique($temp);
        $option_views = array_intersect($temp, $option_user_check);
        $option_views = array_values($option_views);
        
        
        // Tùy chọn hiển thị cho equipment và item
		$arr_name = array();
		$arr_header = array();
        $arr_option_equipment = array('equipmentId','isGeneral','trackDate');
        $arr_option_item = array();
        foreach($option_views as $row){
        	$arr_name[] = $this->_config->views->$row->column;                      // Tất cả các cột cần hiển thị
        	$arr_header[] = $this->_config->views->$row->header;                    // Tên các cột cần hiển thị
            if($this->_config->views->$row->table == 'equipment')           
                $arr_option_equipment[] = $this->_config->views->$row->column;      // Các cột cần hiển thị trong table equipment
            if($this->_config->views->$row->table == 'items')
                $arr_option_item[] = $this->_config->views->$row->column;           // Các cột cần hiển thị trong table items
        }
        $this->view->arr_name = $arr_name;
        $this->view->arr_header = $arr_header;
        $this->view->arr_option_equipment = $arr_option_equipment;
        $this->view->arr_option_item = $arr_option_item;
        
        // Danh sách các dự án mà user có quyền thao tác
        $provilege_role     = $model_rolesprivilege->getDataByUserId($this->_arrParam['userId']);
        $temp = array();
        foreach($provilege_role as $row){
            $temp = array_merge($temp, json_decode($row['projectId']));
        }
        $temp = array_unique($temp);
        $project_list = array_values($temp);
        
        // Lấy danh sách equipment (Chỉ lấy những trường user cần xem)
        $equipment_list = $model_equipment->getNotifyData($project_list, $arr_option_equipment, $this->_paniging['page'], $this->_paniging['rowCount'])->toArray();
        $equipment_count = $model_equipment->countNotifyData($project_list)->toArray();
        
        foreach($equipment_list as $key=>$row){
                //$equipment_list[$key]['items_list'] = $model_items->getDataByEquipmentId($row['equipmentId'],$arr_option_item)->toArray();
                $equipment_list[$key]['items_list'] = $model_items->getItems($row['equipmentId'])->toArray();
                $equipment_list[$key]['project_list'] = $model_project->getDataByEquipmentId($row['equipmentId'])->toArray();
        }
        //echo '<pre>',print_r($equipment_list),'</pre>';exit;
        $this->view->equipment_list = $equipment_list;
        
        
        $objPaginator= new My_Paginator();
        $totalItem = $equipment_count['Total'];
        $itemCountPerPage = $this->_paniging['rowCount'];
        $pageRange = $this->_paniging['pageRange'];
        $currentPage = $this->_paniging['page'];
        $panigator = $objPaginator->createPaginator($totalItem, $itemCountPerPage, $pageRange, $currentPage);
        $this->view->panigator = $panigator;
        
	}
    
    
    public function searchAction()
    {
        
        $model_equipment        = new Default_Model_Equipment();
        $model_rolesoption      = new Default_Model_Rolesoption();
        $model_rolesprivilege   = new Default_Model_Rolesprivilege();
        $model_option           = new Default_Model_Option();
        $model_category         = new Default_Model_Category();
        $model_project          = new Default_Model_Project();
        $model_items            = new Default_Model_Items();
        
        $params['keyword'] 		= $this->getRequest()->getParam('keyword', '');//ten de tim kiem
		$params['projectId'] 	= $this->getRequest()->getParam('projectId', '');
		$params['categoryId'] 	= $this->getRequest()->getParam('categoryId', '');
		$params['ownerId'] 		= $this->getRequest()->getParam('ownerId', '');
		$params['isGeneral'] 	= $this->getRequest()->getParam('isGeneral', -1);
		$params['submit'] 	    = $this->getRequest()->getParam('btn-search');
		$params['page']      	= $this->getRequest()->getParam('page');
        $params['multi']        =$this->getRequest()->getParam('mul');
        $params['itemId']       =$this->getRequest()->getParam('id');
        
        if(is_array($params['projectId']) && !$params['projectId'][0]){
            $params['projectId'] = '';
        }
        if(is_array($params['categoryId']) && !$params['categoryId'][0]){
            $params['categoryId'] = '';
        }
        if(is_array($params['ownerId']) && !$params['ownerId'][0]){
            $params['ownerId'] = '';
        }
        
        if(!is_array($params['projectId']) && $params['projectId']){
            $temp = array();
            $temp[0] = $params['projectId'];
            $params['projectId'] = $temp;
        }
        if(!is_array($params['categoryId']) && $params['categoryId']){
            $temp = array();
            $temp[0] = $params['categoryId'];
            $params['categoryId'] = $temp;
        }
        if(!is_array($params['ownerId']) && $params['ownerId']){
            $temp = array();
            $temp[0] = $params['ownerId'];
            $params['ownerId'] = $temp;
        }
        
        $this->view->keyword = $params['keyword'];
        $this->view->project = $params['projectId'];
        $this->view->category = $params['categoryId'];
        $this->view->owner = $params['ownerId'];
        $this->view->general = $params['isGeneral'];
        
        // Danh sách các dự án mà user có quyền thao tác
        $provilege_role     = $model_rolesprivilege->getDataByUserId($this->_arrParam['userId']);
      
        $temp = array();
        foreach($provilege_role as $row){
            $temp = array_merge($temp, json_decode($row['projectId']));
        }
        $temp = array_unique($temp);
        $project_list = array_values($temp);
        
        $sortCate               = $model_category->getAllData()->toArray();
        $sortProject            = $model_project->getListData($project_list)->toArray();
        $sortOwner              = $model_items->getOwner()->toArray();
        $this->view->sortCate = $sortCate;
        $this->view->sortProject = $sortProject;
        $this->view->sortOwner = $sortOwner;
            
        if($params['submit'] || $params['page']){
		    // lấy phần chung: tùy chọn view của user và tùy chọn view của quyền user
            $option_user_check  = $model_option->getOptions($this->_arrParam['userId'])->toArray();
            $option_user_check  = json_decode($option_user_check['name']);
            
            $option_role        = $model_rolesoption->getDataByUserId($this->_arrParam['userId']);
            $temp = array();
            foreach($option_role as $row){
                $temp = array_merge($temp, json_decode($row['views']));
            }
            $temp = array_unique($temp);
            $option_views = array_intersect($temp, $option_user_check);
            $option_views = array_values($option_views);

            // Tùy chọn hiển thị cho equipment và item
    		$arr_name = array();
    		$arr_header = array();
            $arr_option_equipment = array('equipmentId','isGeneral','trackDate');
            $arr_option_item = array();
            foreach($option_views as $row){
            	$arr_name[] = $this->_config->views->$row->column;                      // Tất cả các cột cần hiển thị
            	$arr_header[] = $this->_config->views->$row->header;                    // Tên các cột cần hiển thị
                if($this->_config->views->$row->table == 'equipment')           
                    $arr_option_equipment[] = $this->_config->views->$row->column;      // Các cột cần hiển thị trong table equipment
                if($this->_config->views->$row->table == 'items')
                    $arr_option_item[] = $this->_config->views->$row->column;           // Các cột cần hiển thị trong table items
            }
            $this->view->arr_name = $arr_name;
            $this->view->arr_header = $arr_header;
            $this->view->arr_option_equipment = $arr_option_equipment;
            $this->view->arr_option_item = $arr_option_item;

            // Lấy danh sách equipment (Chỉ lấy những trường user cần xem)
            $equipment_list = $model_equipment->getSearchData($params['keyword'],$params['categoryId'],$params['projectId'],$params['ownerId'],$params['isGeneral'],$project_list, $arr_option_equipment, $this->_paniging['page'], $this->_paniging['rowCount'])->toArray();
            $equipment_count = $model_equipment->countSearchData($params['keyword'],$params['categoryId'],$params['projectId'],$params['ownerId'],$params['isGeneral'],$project_list)->toArray();
           
            foreach($equipment_list as $key=>$row){
                    //$equipment_list[$key]['items_list'] = $model_items->getDataByEquipmentId($row['equipmentId'],$arr_option_item)->toArray();
                $equipment_list[$key]['items_list'] = $model_items->getItems($row['equipmentId'])->toArray();
                $equipment_list[$key]['project_list'] = $model_project->getDataByEquipmentId($row['equipmentId'])->toArray();
            }
            //echo '<pre>',print_r($equipment_list),'</pre>';exit;
            $this->view->equipment_list = $equipment_list;
            
            $objPaginator= new My_Paginator();
            $totalItem = $equipment_count['Total'];
            $itemCountPerPage = $this->_paniging['rowCount'];
            $pageRange = $this->_paniging['pageRange'];
            $currentPage = $this->_paniging['page'];
            
            $panigator = $objPaginator->createPaginator($totalItem, $itemCountPerPage, $pageRange, $currentPage);
            $this->view->panigator = $panigator;
            $this->view->search = 1;
        }else{
            $this->view->search = 0;
        }
        if(isset($params['multi']) && $params['multi'])
        {
            $this->view->itemId= $params['itemId']; 
            $option=array(
			"layout" => "layoutfancy",
			"layoutPath" => APPLICATION_PATH."/layouts/scripts/"
		  );
		  Zend_Layout::startMvc($option);
            $this->renderScript('equipment/search-e.phtml');
            
        }
    }
	public function exportexcelAction()
	{
	    Zend_Layout::getMvcInstance()->disableLayout();
	    $this->_helper->viewRenderer->setNoRender();
        	 
        $model_equipment        = new Default_Model_Equipment();
        $model_rolesprivilege   = new Default_Model_Rolesprivilege();
        $model_category         = new Default_Model_Category();
        $model_project          = new Default_Model_Project();
        $model_items            = new Default_Model_Items();
        $helper_time            = $this->_helper->time;
        
        // Danh sách các dự án mà user có quyền thao tác
        $provilege_role     = $model_rolesprivilege->getDataByUserId($this->_arrParam['userId']);
        $temp = array();
        foreach($provilege_role as $row){
            $temp = array_merge($temp, json_decode($row['projectId']));
        }
        $temp = array_unique($temp);
        $project_list = array_values($temp);
        
		$params['type'] 		= $this->getRequest()->getParam('type', '');
        if(isset($params['type']) && $params['type'] == 'searchequipment'){
    		$params['keyword'] 		= $this->getRequest()->getParam('search_keyword', '');
    		$params['projectId'] 	= $this->getRequest()->getParam('search_project', '');
    		$params['categoryId'] 	= $this->getRequest()->getParam('search_category', '');
    		$params['ownerId'] 		= $this->getRequest()->getParam('search_owner', '');
    		$params['isGeneral'] 	= $this->getRequest()->getParam('search_general', -1);
            if(is_array($params['projectId']) && !$params['projectId'][0]){
                $params['projectId'] = '';
            }
            if(is_array($params['categoryId']) && !$params['categoryId'][0]){
                $params['categoryId'] = '';
            }
            if(is_array($params['ownerId']) && !$params['ownerId'][0]){
                $params['ownerId'] = '';
            }
            
            if(!is_array($params['projectId']) && $params['projectId']){
                $temp = array();
                $temp[0] = $params['projectId'];
                $params['projectId'] = $temp;
            }
            if(!is_array($params['categoryId']) && $params['categoryId']){
                $temp = array();
                $temp[0] = $params['categoryId'];
                $params['categoryId'] = $temp;
            }
            if(!is_array($params['ownerId']) && $params['ownerId']){
                $temp = array();
                $temp[0] = $params['ownerId'];
                $params['ownerId'] = $temp;
            }
            //echo '<pre>',print_r($params),'</pre>';exit();
            $equipment_list = $model_equipment->getExcelData($params['keyword'],$params['categoryId'],$params['projectId'],$params['ownerId'],$params['isGeneral'],$project_list)->toArray( );
        }elseif(isset($params['type']) && $params['type'] == 'allequipment'){
    		$params['keyword'] 		= $this->getRequest()->getParam('search_keyword', '');
    		$params['projectId'] 	= $this->getRequest()->getParam('search_project', '');
    		$params['categoryId'] 	= $this->getRequest()->getParam('search_category', '');
    		$params['ownerId'] 		= $this->getRequest()->getParam('search_owner', '');
    		$params['isGeneral'] 	= $this->getRequest()->getParam('search_general', -1);
            if(is_array($params['projectId']) && !$params['projectId'][0]){
                $params['projectId'] = '';
            }
            if(is_array($params['categoryId']) && !$params['categoryId'][0]){
                $params['categoryId'] = '';
            }
            if(is_array($params['ownerId']) && !$params['ownerId'][0]){
                $params['ownerId'] = '';
            }
            
            if(!is_array($params['projectId']) && $params['projectId']){
                $temp = array();
                $temp[0] = $params['projectId'];
                $params['projectId'] = $temp;
            }
            if(!is_array($params['categoryId']) && $params['categoryId']){
                $temp = array();
                $temp[0] = $params['categoryId'];
                $params['categoryId'] = $temp;
            }
            if(!is_array($params['ownerId']) && $params['ownerId']){
                $temp = array();
                $temp[0] = $params['ownerId'];
                $params['ownerId'] = $temp;
            }
            //echo '<pre>',print_r($params),'</pre>';exit();
            
            $equipment_list = $model_equipment->getExcelData($params['keyword'],$params['categoryId'],$params['projectId'],$params['ownerId'],$params['isGeneral'],$project_list)->toArray( );
        }elseif(isset($params['type']) && $params['type'] == 'serverfree'){
            $project_list_34 		= $this->getRequest()->getParam('project_34');
            $project_list_38 		= $this->getRequest()->getParam('project_38');
            $project_list_47 		= $this->getRequest()->getParam('project_47');
            $project_list = array();
            if($project_list_34)
                $project_list[] = 34;
            if($project_list_38)
                $project_list[] = 38;
            if($project_list_47)
                $project_list[] = 47;
                
            if(!isset($project_list[0])){
                $project_list = array(34,38,47);
                $project_list_34 = 34;
                $project_list_38 = 38;
                $project_list_47 = 47;
            }
            $equipment_list = $model_equipment->getServerFreeExcelData($project_list)->toArray();
        
        }elseif(isset($params['type']) && $params['type'] == 'notify'){
            $equipment_list = $model_equipment->getNotifyExcelData($project_list)->toArray();
        }
        if($equipment_list){
            foreach($equipment_list as $key=>$row){
                $item_list = $model_items->getItems($row['equipmentId'])->toArray();
                $project_equipment_list = $model_project->getDataByEquipmentId($row['equipmentId'])->toArray();
                if($item_list)
                    $equipment_list[$key]['item_list'] = $item_list;
                if($project_equipment_list)
                    $equipment_list[$key]['project_list'] = $project_equipment_list;
            }
            //echo '<pre>',print_r($equipment_list),'</pre>';exit();
            error_reporting(E_ERROR | E_WARNING | E_PARSE);
    			
            $workbook = My_Pear::getInstanceSpreadsheet();
    	    $workbook->setVersion(8, 'utf-8'); 
    		$worksheet1 = &$workbook->addWorksheet('worksheet 1'); 
            $worksheet1->setInputEncoding('utf-8');
            $worksheet1->setColumn(0,0,6);
            $worksheet1->setColumn(1,2,15);
            $worksheet1->setColumn(3,6,10);
            $worksheet1->setColumn(7,7,50);
            $worksheet1->setColumn(14,14,50);
            $worksheet1->setColumn(19,20,12);
            $worksheet1->setColumn(21,21,30);
            $worksheet1->setColumn(24,24,30);
            
    		//end style	
    		$header = &$workbook->addFormat(); 
    		$header->setBold(); 
    		$header->setColor('white'); 
            $header->setFgColor('50'); 
    		$header->setAlign('vcentre');
    		$header->setHAlign('center'); 
    		$header->setVAlign('center'); 
    		$header->setBorder(1); 	
            $header->setTextWrap();
    
    		$textStyle = &$workbook->addFormat(); 
    		$textStyle->setAlign('vcentre');
    		$textStyle->setHAlign('center'); 
    		$textStyle->setVAlign('center'); 
    		$textStyle->setHAlign('left');
            $textStyle->setBorder(1);
            $textStyle->setTextWrap();
    
    		$textStyleYellow = &$workbook->addFormat(); 
    		$textStyleYellow->setFgColor('43'); 
    		$textStyleYellow->setAlign('vcentre');
    		$textStyleYellow->setHAlign('center'); 
    		$textStyleYellow->setVAlign('center'); 
    		$textStyleYellow->setHAlign('left');
            $textStyleYellow->setBorder(1);
            $textStyleYellow->setTextWrap();
    
    		$textStyleBlue = &$workbook->addFormat(); 
    		$textStyleBlue->setFgColor('41'); 
    		$textStyleBlue->setAlign('vcentre');
    		$textStyleBlue->setHAlign('center'); 
    		$textStyleBlue->setVAlign('center'); 
            $textStyleBlue->setBorder(1);
            $textStyleBlue->setTextWrap();
    
    		$textStyleCyan = &$workbook->addFormat(); 
    		$textStyleCyan->setFgColor('22'); 
    		$textStyleCyan->setAlign('vcentre');
    		$textStyleCyan->setHAlign('center'); 
    		$textStyleCyan->setVAlign('center'); 
    		$textStyleCyan->setHAlign('left');
            $textStyleCyan->setBorder(1);
            $textStyleCyan->setTextWrap();
    		
    		$numberSTTFormat = &$workbook->addFormat();
    		$numberSTTFormat->setAlign('vcentre');
    		$numberSTTFormat->setHAlign('center'); 
    		$numberSTTFormat->setVAlign('center'); 
    		$numberSTTFormat->setNumFormat('#,###');
            $numberSTTFormat->setBorder(1);
            $numberSTTFormat->setTextWrap();
    		
    		$numberSTTFormatYellow = &$workbook->addFormat();
    		$numberSTTFormatYellow->setFgColor('43'); 
    		$numberSTTFormatYellow->setAlign('vcentre');
    		$numberSTTFormatYellow->setHAlign('center'); 
    		$numberSTTFormatYellow->setVAlign('center'); 
    		$numberSTTFormatYellow->setNumFormat('#,###');
            $numberSTTFormatYellow->setBorder(1);
            $numberSTTFormatYellow->setTextWrap();
    		
    		$numberSTTFormatBlue = &$workbook->addFormat();
    		$numberSTTFormatBlue->setFgColor('41'); 
    		$numberSTTFormatBlue->setAlign('vcentre');
    		$numberSTTFormatBlue->setHAlign('center'); 
    		$numberSTTFormatBlue->setVAlign('center'); 
    		$numberSTTFormatBlue->setNumFormat('#,###');
            $numberSTTFormatBlue->setBorder(1);
            $numberSTTFormatBlue->setTextWrap();
    		
    		$numberSTTFormatCyan = &$workbook->addFormat();
    		$numberSTTFormatCyan->setFgColor('22'); 
    		$numberSTTFormatCyan->setAlign('vcentre');
    		$numberSTTFormatCyan->setHAlign('center'); 
    		$numberSTTFormatCyan->setVAlign('center'); 
    		$numberSTTFormatCyan->setNumFormat('#,###');
            $numberSTTFormatCyan->setBorder(1);
            $numberSTTFormatCyan->setTextWrap();
    		
    		$numberFormat = &$workbook->addFormat();
    		$numberFormat->setHAlign('right');
    		$numberFormat->setVAlign('center'); 
    		$numberFormat->setNumFormat('#,###');
            $numberFormat->setBorder(1);
            $numberFormat->setTextWrap();
    		
    		$numberFormatYellow = &$workbook->addFormat();
    		$numberFormatYellow->setFgColor('43'); 
    		$numberFormatYellow->setHAlign('right');
    		$numberFormatYellow->setVAlign('center'); 
    		$numberFormatYellow->setNumFormat('#,###');
            $numberFormatYellow->setBorder(1);
            $numberFormatYellow->setTextWrap();
    		
    		$numberFormatBlue = &$workbook->addFormat();
    		$numberFormatBlue->setFgColor('41'); 
    		$numberFormatBlue->setHAlign('right');
    		$numberFormatBlue->setVAlign('center'); 
    		$numberFormatBlue->setNumFormat('#,###');
            $numberFormatBlue->setBorder(1);
            $numberFormatBlue->setTextWrap();
    		
    		$numberFormatCyan = &$workbook->addFormat();
    		$numberFormatCyan->setFgColor('22'); 
    		$numberFormatCyan->setHAlign('right');
    		$numberFormatCyan->setVAlign('center'); 
    		$numberFormatCyan->setNumFormat('#,###');
            $numberFormatCyan->setBorder(1);
            $numberFormatCyan->setTextWrap();
            
            
            //title
            $option_views = $this->_config->views;
            $stt = 1;
            foreach($option_views as $row){
            	$arr_name[] = $this->_config->views->$stt->column;                      // Tất cả các cột cần hiển thị
            	$arr_header[] = $this->_config->views->$stt->header;                    // Tên các cột cần hiển thị
                $arr_table[] = $this->_config->views->$stt->table;                      // Table các cột cần hiển thị
                if($this->_config->views->$stt->table == 'equipment')           
                    $arr_option_equipment[] = $this->_config->views->$stt->column;      // Các cột cần hiển thị trong table equipment
                if($this->_config->views->$stt->table == 'items')
                    $arr_option_item[] = $this->_config->views->$stt->column;           // Các cột cần hiển thị trong table items
                ++$stt;
            }	
            $num_column = 1;
                $worksheet1->write(0, 0, 'STT', $header); 
            foreach($arr_header as $row){
                $worksheet1->write(0, $num_column, $row, $header); 
                ++$num_column;
            }
            //end title
            
            //Ghi dữ liệu equipment
            $stt = 1;
            $num_row = 1;
            // vòng lặp các record equipment
            foreach($equipment_list as $equipment){
                $typeText = $textStyle;
                $typeNumb = $numberFormat;
                $typeSTT = $numberSTTFormat;
// đan màu chẵn lẻ
//                if($stt % 2 == 1){
//                    $typeText = $textStyleCyan;
//                    $typeNumb = $numberFormatCyan;
//                }else{
//                    $typeText = $textStyle;
//                    $typeNumb = $numberFormat;
//                }
                if(isset($equipment['isGeneral']) && $equipment['isGeneral'] == 1){
                    $typeText = $textStyleYellow;
                    $typeNumb = $numberFormatYellow;
                    $typeSTT = $numberSTTFormatYellow;
                }
                if(isset($equipment['trackDate']) && $equipment['trackDate'] > date("Y-m-d")){
                    $typeText = $numberFormatBlue;
                    $typeNumb = $numberFormatBlue;
                    $typeSTT = $numberSTTFormatBlue;
                }
                
                $worksheet1->write($num_row, 0, $stt, $typeSTT); 
                $num_column = 1;
                //vòng lặp các giá trị
                $count = count($equipment['item_list']);
                foreach($arr_name as $key=>$value){
                    if($arr_table[$key] == 'equipment' || $arr_table[$key] == 'users' || $arr_table[$key] == 'category'){
                        if($equipment[$value]){
                            $worksheet1->writeString($num_row, $num_column, $equipment[$value], $typeText);
                        }else{
                            $worksheet1->writeString($num_row, $num_column, "", $typeText);
                        }
                        for($i = 1; $i < $count; $i++){
                            $worksheet1->writeString($num_row + $i, $num_column, "", $typeText);
                        }
                        if($count > 1){
                            $worksheet1->setMerge($num_row, $num_column, $num_row+$count-1, $num_column);
                            $worksheet1->setMerge($num_row, 0, $num_row+$count-1, 0);
                        }
                    }elseif($arr_table[$key] == 'project'){
                        if($equipment['project_list']){
                            if($equipment['project_list']){
                                $temp = 0;
                                $strValue = '';
                                foreach($equipment['project_list'] as $project){
                                    if($temp == 0)
                                        $strValue .= $project["projectName"];
                                    else
                                        $strValue .= "; ".$project["projectName"];
                                    ++$temp;
                                }    
                                $worksheet1->writeString($num_row, $num_column, $strValue, $typeText);
                            }else{
                                $worksheet1->writeString($num_row, $num_column, "", $typeText);
                            }
                        }
                        for($i = 1; $i < $count; $i++){
                            $worksheet1->writeString($num_row + $i, $num_column, "", $typeText);
                        }
                        if($count > 1){
                            $worksheet1->setMerge($num_row, $num_column, $num_row+$count-1, $num_column);
                            $worksheet1->setMerge($num_row, 0, $num_row+$count-1, 0);
                        }
                    }else{
                        if($equipment['item_list']){
                            $num_row_temp = $num_row;
                            $countItem = 1;                                                        
                            foreach($equipment['item_list'] as $item){                                                       
                                if($item[$value]){
                                    if($value == 'rentItem' || $value == 'priceItem' || $value == 'priceNow' || $value == 'rentEnd'){
                                        $numb = (int)(str_replace(array(".",","), array("",""), $item[$value]));
                                        $worksheet1->writeNumber($num_row_temp, $num_column, $numb, $typeNumb);
                                    }elseif($value == 'startDate' || $value == 'duration'){
                                        if($item[$value] != '0000-00-00 00:00:00'){
                                            $time = $helper_time->dataToDate($item[$value]);
                                            $worksheet1->writeString($num_row_temp, $num_column, $time, $typeText);
                                        }else{
                                            $worksheet1->writeString($num_row_temp, $num_column, "", $typeText);
                                        }
                                    }else{
										$val = utf8_encode($item[$value], "utf-8");
                                        $worksheet1->writeString($num_row_temp, $num_column, $item[$value], $typeText);
                                    }
                                }else{
                                    $worksheet1->writeString($num_row_temp, $num_column, "", $typeText);
                                }
                                ++$countItem; 
                                ++$num_row_temp;
                            }
                        }
                    }
                        
                    ++$num_column;
                }
                if(is_array($equipment['item_list']))
                    $num_row = $num_row + count($equipment['item_list']);
                else
                    ++$num_row;
                ++$stt;
            }
            
    		$name = "cmdb_equipment_".date("dmY");
    		$workbook->send("{$name}.xls"); 
    		$workbook->close();
        }else{	
			echo 'Dữ liệu không có! Vui lòng kiểm tra lại!';
			return $this->_helper->redirector('index', 'equipment');
		}
    }
    public function deleteAction()
    {
        if($this->getRequest()->isPost()){
            $del = $this->getRequest()->getPost('del');
            if($del == 'Có'){
                $equipmentId = $this->getRequest()->getPost('equipmentId');
                $model_equipment = new Default_Model_Equipment();
                $model_equipment->deleteEquipment($equipmentId, $this->_userInfo['username']);
                //Xóa các chi tiết con
                $equipmentProjectModel = new Default_Model_EquipmentProject();
                $equipmentProjectModel->deleteProjectByEquipmentId($equipmentId);
                $itemModel = new Default_Model_Items();
                $itemModel->deleteItemByEquipment($equipmentId);
            }
            $this->_helper->redirector('index');
        }else{
            $id = $this->_getParam('id', 0);
            $model_equipment = new Default_Model_Equipment();
            $this->view->equipment = $model_equipment->getDataById($id);
        }
    }

    public function detailAction ()
    {
    	$id = $this->_getParam('id',0);
        $model_option           = new Default_Model_Option();
        $model_rolesoption      = new Default_Model_Rolesoption();
                
        // lấy phần chung: tùy chọn view của user và tùy chọn view của quyền user
        $option_user_check  = $model_option->getOptions($this->_userInfo['userId'])->toArray();
        $option_user_check  = json_decode($option_user_check['name']);
        
        $option_role        = $model_rolesoption->getDataByUserId($this->_arrParam['userId']);
        $temp = array();
        foreach($option_role as $row){
            $temp = array_merge($temp, json_decode($row['views']));
        }
        $temp = array_unique($temp);
        $option_views = array_intersect($temp, $option_user_check);
        $option_views = array_values($option_views);
        
        // Tùy chọn hiển thị cho equipment và item
		$arr_option_equipment = array();
        $arr_option_item = array();
        foreach($option_views as $row){
        	if($this->_config->views->$row->table == 'equipment'){           
                $arr_option_equipment[] = array('column'=>$this->_config->views->$row->column,'header'=>$this->_config->views->$row->header);
            }
            if($this->_config->views->$row->table == 'items'){
                $arr_option_item[] = array('column'=>$this->_config->views->$row->column,'header'=>$this->_config->views->$row->header);
            }
        }
        $this->view->arr_option_equipment = $arr_option_equipment;
        $this->view->arr_option_item = $arr_option_item;
        
    	$model_equipment = new Default_Model_Equipment();
    	$equipment = $model_equipment->getDataById($id);
    	$this->view->equipment = $equipment;
    }
    public function addAction ()
    {
        $form = new Default_Form_Equipment();
        $form->submit->setLabel('Thêm mới!');
        $this->view->form = $form;
        
        $owner_list = $this->_config->owner->toArray();
        $this->view->owner_list = $owner_list;
        
        $model_holder = new Default_Model_Holder();
        $holder_list = $model_holder->getAllData();
        $temp = '';
        $stt = 1;
        foreach($holder_list as $row){
            if($stt != 1){
                $temp .= ', ';
            }
            $temp .= '"'.$row['holderName'].'"';
            ++$stt;
        }
        $this->view->holder_list = $temp;
        
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
            	$duration = $this->_getParam('duration');
	            $startDate = $this->_getParam('startDate');				
				for($i = 0, $count = count($duration); $i<$count; ++$i){
					if($duration[$i] != 0){
						$mathDate = strtotime($duration[$i]) - strtotime($startDate[$i]);
						if($mathDate <= 0){
							$msg = "Thời gian phải lớn hơn ngày bắt đầu. Vui lòng nhập lại thông tin chính xác!!!";
						}
					}
				}
				for($i = 0, $count = count($startDate); $i<$count; ++$i){
				    if($startDate[$i] > 0){
                        $startDate[$i] = date("Y-m-d",strtotime($startDate[$i]));
                    }else{
                        $startDate = 0;
                    }
                    if($duration[$i] > 0){
                        $duration[$i] = date("Y-m-d",strtotime($duration[$i]));
                    }else{
                        $duration[$i] = 0;
                    }
                }
                                                                
				if(isset($msg)){
					$this->view->errorDate = $msg;
				}else{
	                $equipmentName	= $form->getValue('equipmentName');
	                $code 			= $form->getValue('code');
	                $info 			= $this->_getParam('info');
	                $addendums 		= $this->_getParam('addendums');
	                $serialNumber   = $this->_getParam('serialNumber');
	                $position 		= $form->getValue('position');
	                $function 		= $form->getValue('function');
	                $owner 			= $this->_getParam('owner');
	                $holders 		= $this->_getParam('holders');
	                $endUser 		= $form->getValue('endUser');
	                $price 			= str_replace('.','',$this->_getParam('priceNow'));
	                $history 		= $this->_getParam('history');
	                $managerId 		= $form->getValue('managerId');
	                $note 			= $form->getValue('note');
	                $item 			= $this->_getParam('item');
	                $rentItem 		= str_replace('.','',$this->_getParam('rentItem'));
	                $rentEnd 		= str_replace('.','',$this->_getParam('rentEnd'));
	                $priceItem 		= str_replace('.','',$this->_getParam('priceItem'));
					$expire 		= $this->_getParam('endTime');
					for($i = 0, $count = count($expire); $i < $count; ++$i){
						if($expire[$i] != ""){
							$expire[$i] = 1;
						}else{
							$expire[$i] = 0;
						}						
					}

	                $ip 			= $form->getValue('ip');
	                $ipWan 			= $form->getValue('ipWan');
	                $trackDate 	    = $form->getValue('trackDate');
                    
                    if($trackDate > 0){
                        $trackDate = date("Y-m-d",strtotime($trackDate));
                        $trackContent 	= $form->getValue('trackContent');
                    }else{
                        $trackDate = 0;
                        $trackContent = "";
                    }
	                $categoryId 	= $form->getValue('categoryId');
	                $projectId 		= $form->getValue('projectId');
					$params 		= $form->getValue('params');
					$checkGeneral 	= $form->getValue('isGeneral');
					$borrow         = $form->getValue('borrow');
					if(count($params) > 1){
						$useGeneral = $params[0];
						for($i =1, $count = count($params); $i < $count; ++$i)
							$useGeneral .=  ", " . $params[$i]; 
					}else if(count($params) == 1){
						$useGeneral = $params[0];
					}else{
						$useGeneral = "";
					}
                    foreach($holders as $row){
                        $holder_check = $model_holder->getDataByName($row);
                        if(!$holder_check){
                            $model_holder->addData($row);
                        }
                    }
					$data = array('equipmentName' => $equipmentName, 'code'=>$code, 'position'=>$position,
									'function'=>$function, 'endUser'=>$endUser, 'managerId'=>$managerId, 'note'=>$note,									
									'ip' => $ip, 'ipWan'=>$ipWan, 'trackDate'=>$trackDate, 'trackContent'=>$trackContent, 'categoryId'=>$categoryId, 'params'=>$useGeneral, 'isGeneral'=>$checkGeneral, 'borrow'=>$borrow, 
                                    'createUser' => $this->_userInfo['userId'], 'createDate' => date('Y-m-d H:i:s'));									
	                $model_equipment = new Default_Model_Equipment();		
	                $flag =	$model_equipment->addEquipment($data, $info, $addendums, $owner, $holders, $duration, $price, $history, $startDate, $projectId, $item, $rentItem, $priceItem, $expire, $this->_userInfo['username'], $rentEnd, $serialNumber);
	                $this->processResult($flag);
				}
            } else {
                $form->populate($formData);
            }
        }
    }

    public function editAction()
    {
		$form = new Default_Form_Equipment();
		$form->submit->setLabel( 'Lưu' );
		// $form->removeElement('project');
		$this->view->form = $form;		
              
        $owner_list = $this->_config->owner->toArray();
        $temp = '';
        $stt = 1;
        foreach($owner_list as $row){
            if($stt != 1){
                $temp .= ', ';
            }
            $temp .= '"'.$row['name'].'"';
            ++$stt;
        }
        $this->view->owner_list = $temp;
       //"SSGame", "SSGroup", "WinGame", "3S"
        $model_holder = new Default_Model_Holder();
        $holder_list = $model_holder->getAllData();
        $temp = '';
        $stt = 1;
        foreach($holder_list as $row){
            if($stt != 1){
                $temp .= ', ';
            }
            $temp .= '"'.$row['holderName'].'"';
            ++$stt;
        }
        $this->view->holder_list = $temp;
        //"Nguyễn Chí Thuần", "Lê Hoàng Sơn", "Bùi Anh Tuấn", "", "Wingame", "Nguyễn Anh Tuấn", "ssgame", "Vũ Ngọc Long", "3s", "Vinh Quốc Nguyên"
        
		if ($this->getRequest()->isPost()) {
			$model_equipment = new Default_Model_Equipment();
			$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)) {
			$duration = $this->_getParam('duration');
            $startDate = $this->_getParam('startDate');
			for($i = 0, $count = count($duration); $i<$count; ++$i){
				if($duration[$i] != 0){
					$mathDate = strtotime($duration[$i]) - strtotime($startDate[$i]);
					if($mathDate <= 0){
						$msg = "Thời gian phải lớn hơn ngày bắt đầu. Vui lòng nhập lại thông tin chính xác!!!";
					}
				}
			}
			for($i = 0, $count = count($startDate); $i<$count; ++$i){
			    if($startDate[$i] > 0){
                    $startDate[$i] = date("Y-m-d",strtotime($startDate[$i]));
                }else{
                    $startDate = 0;
                }
                if($duration[$i] > 0){
                    $duration[$i] = date("Y-m-d",strtotime($duration[$i]));
                }else{
                    $duration[$i] = 0;
                }
            }
			if(isset($msg)){
				$this->view->errorDate = $msg;
				$id = $this->_getParam('id', 0);
				if ($id > 0) {
					$model_equipment = new Default_Model_Equipment();
					$data = $model_equipment->getDataById($id);
                   
					$this->view->data = $data;

					$form->populate($data);
				}
			}else{

					$equipmentId = $form->getValue('equipmentId');
                    $model_project = new Default_Model_Project();
					$project = $model_project->getDataByEquipmentId($equipmentId);
                   
					if(count($project)==0){
						$this->view->message = 'Thiết bị này chưa được dùng cho dự án nào!!! Bạn vui lòng chọn dự án cho thiết bị!!!';
						return;
					}
					$equipmentName = $form->getValue('equipmentName');
	                $code = $form->getValue('code');
	                $info = $this->_getParam('info');
	                $addendums = $this->_getParam('addendums');
	                $serialNumber = $this->_getParam('serialNumber');
	                $position = $form->getValue('position');
	                $function = $form->getValue('function');
	                $owner = $this->_getParam('owner');
	                $holders = $this->_getParam('holders');
	                $endUser = $form->getValue('endUser');
	                $price = str_replace('.','',$this->_getParam('priceNow'));
	                $history = $this->_getParam('history');
	                $managerId = $form->getValue('managerId');
	                $note = $form->getValue('note');
					$itemId = $this->_getParam('itemId');
	                $item = $this->_getParam('item');
	                $rentItem 		= str_replace('.','',$this->_getParam('rentItem'));
	                $rentEnd 		= str_replace('.','',$this->_getParam('rentEnd'));
	                $priceItem 		= str_replace('.','',$this->_getParam('priceItem'));
					$expire = $this->_getParam('endTime');
					for($i = 0, $count = count($expire); $i< $count; ++$i){
						if($expire[$i] != ""){
							$expire[$i] = 1;
						}else{
							$expire[$i] = 0;
						}
					}
	                //thêm item (nếu có)
	                $item_new = $this->_getParam('item_new');
                    
	                $rentItem_new 		= str_replace('.','',$this->_getParam('rentItem_new'));
	                $rentEnd_new 		= str_replace('.','',$this->_getParam('rentEnd_new'));
	                $priceItem_new 		= str_replace('.','',$this->_getParam('priceItem_new'));
	                $priceNow_new 		= str_replace('.','',$this->_getParam('priceNow_new'));
                    
	                $duration_new = $this->_getParam('duration_new');
	                $startDate_new = $this->_getParam('startDate_new');
	                $info_new = $this->_getParam('info_new');
	                $addendums_new = $this->_getParam('addendums_new');
	                $serialNumber_new = $this->_getParam('serialNumber_new');
	                $history_new = $this->_getParam('history_new');
	                $owner_new = $this->_getParam('owner_new');
	                $holders_new = $this->_getParam('holders_new');
					$expire_new = $this->_getParam('endTime_new');
					for($i = 0, $count = count($expire_new); $i< $count; ++$i){
						if($expire_new[$i] != ""){
							$expire_new[$i] = 1;
						}else{
							$expire_new[$i] = 0;
						}
					}
        			for($i = 0, $count = count($startDate_new); $i<$count; ++$i){
        			    if($startDate_new[$i] > 0){
                            $startDate_new[$i] = date("Y-m-d",strtotime($startDate_new[$i]));
                        }else{
                            $startDate_new = 0;
                        }
                        if($duration_new[$i] > 0){
                            $duration_new[$i] = date("Y-m-d",strtotime($duration_new[$i]));
                        }else{
                            $duration_new[$i] = 0;
                        }
                    }
	                $ip 			= $form->getValue('ip');
	                $ipWan 			= $form->getValue('ipWan');
                    $trackDate      = $form->getValue('trackDate');
                    if($trackDate > 0){
                        $trackDate = date("Y-m-d",strtotime($trackDate));
                        $trackContent = $form->getValue('trackContent');
                    }else{
                        $trackDate = 0;
                        $trackContent = "";
                    }
	                $categoryId 	= $form->getValue('categoryId');
					$params 		= $form->getValue('params');
					$projectId 		= $form->getValue('projectId');
					if(count($params) > 1){
						$useGeneral = $params[0];
						for($i =1, $count = count($params); $i < $count; ++$i)
							$useGeneral .= ", " . $params[$i]; 
					}else if(count($params) == 1){
						$useGeneral = $params[0];
					}else{
						$useGeneral = "";
					}
					        
                    foreach($holders as $row){
                        $holder_check = $model_holder->getDataByName($row);
                        if(!$holder_check){
                            $model_holder->addData($row);
                        }
                    }
                                
					$checkGeneral 	= $form->getValue('isGeneral');
					$borrow         = $form->getValue('borrow');
					$data = array('equipmentId'=>$equipmentId, 'equipmentName' => $equipmentName, 'code'=>$code, 'position'=>$position,
									'function'=>$function, 'endUser'=>$endUser, 'managerId'=>$managerId, 'note'=>$note,									
									'ip' => $ip, 'ipWan'=>$ipWan, 'trackDate'=>$trackDate, 'trackContent'=>$trackContent, 'categoryId'=>$categoryId, 'params'=>$useGeneral, 'isGeneral'=>$checkGeneral, 'borrow'=>$borrow,
                                    'updateUser'=> $this->_arrParam['userId'],'updateDate'=> date("Y-m-d H:i:s"));	
									
					$model_equipment->updateEquipment($data, $info, $addendums, $owner, $holders, $duration, $price, $history, $startDate, $itemId, $item, $rentItem, $priceItem, $expire, $item_new, $rentItem_new, $rentEnd_new, $priceItem_new, $priceNow_new, $duration_new, $startDate_new, $info_new, $addendums_new, $history_new, $owner_new, $holders_new, $expire_new, $this->_userInfo['userId'], $projectId, $rentEnd, $serialNumber);

					$this->_helper->redirector('index');
				}
			} else {
				//edit item :: 07/11/2012 ::
				$item = array();

				for($i = 0; $i<count($formData['itemId']); ++$i){
					$item[] = (object)array("itemId" => $formData['itemId'][$i], "itemName" => $formData['item'][$i], 'priceItem' => $formData['priceItem'][$i], 'rentItem' => $formData['rentItem'][$i]);
				}
				if(isset($formData['item_new'])){
					for($i = 0; $i<count($formData['item_new']); ++$i){
						$item[] = (object)array("itemName" => $formData['item_new'][$i], 'priceItem' => $formData['priceItem_new'][$i], 'rentItem' => $formData['rentItem_new'][$i]);
					}
				}
			
				$this->view->item = $item;
				$form->populate($formData);
				//edit item :: 07/11/2012 ::
			}
		}else{
			$id = $this->_getParam('id', 0);
			if ($id > 0) {
				$model_equipment = new Default_Model_Equipment();
				$data = $model_equipment->getDataById($id);	
                
				$this->view->data = $data;
                
				$params = explode(', ', $data['params']);
				$data['params'] = $params;			
                $data['trackDate'] = $this->_helper->time->dataTimeToDateTime_3($data['trackDate']);		
                //echo '<pre>',print_r($data),'<pre>';	exit();	
				$form->populate($data);
			}
		}
    }
   
 

	public function processResult($code)
	{
		switch ($code)
		{
			case 23000:
				$this->view->message = "Mã quản lý đã tồn tại";
				break;
			default:
				$this->_helper->redirector('index');

		}
	}
}






